<template>
  <div class="workExperience-list">
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="Home" :replace="true">首页</el-breadcrumb-item>
        <el-breadcrumb-item>工作经历列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-form :inline="true" :model="workExperienceQueryForm" ref="workExperienceQueryFormRef" :rules="rules">
      <el-form-item label="员工姓名" prop="employeeName">
        <el-input v-model="workExperienceQueryForm.employeeName" placeholder="请选择员工姓名" readonly="readonly">
          <template #suffix>
            <el-icon @click="findEmployee"><Search/></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="onAdd">新增</el-button>
        <el-button type="primary" @click="onExport">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="state.tableData"
      border
      v-loading="state.loading"
      size="small"
      header-cell-class-name="table-header-cell-font"
      cell-class-name="table-cell-font">
      <el-table-column prop="employeeName" label="员工姓名"></el-table-column>
      <el-table-column prop="company" label="公司名称"></el-table-column>
      <el-table-column prop="position" label="岗位"></el-table-column>
      <el-table-column prop="startDate" label="开始日期"></el-table-column>
      <el-table-column prop="endDate" label="结束日期"></el-table-column>
      <el-table-column label="岗位职责">
        <template v-slot="{ row }">
          <div class="ellipsis">
            {{ row.responsibilities }}
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="250">
        <template v-slot="{ row }">
          <el-button @click.prevent="editRow(row.id)" type="primary">编辑</el-button>
          <el-button @click.prevent="delRow(row.id)" type="danger" plain>删除</el-button>
          <el-button @click.prevent="detailRow(row.id)" type="primary" plain>详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-pagination">
      <el-pagination
        @current-change="changePage"
        :current-page="state.currentPage"
        :page-sizes="state.pageSizes"
        :page-size="state.pageSize"
        background
        layout="total, prev, pager, next, jumper"
        :total="state.total">
      </el-pagination>
    </div>
    <el-dialog v-model="employeeSelectorVisible" v-if="employeeSelectorVisible" title="员工基本信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <employee-selector @employee-selected-event="handleEmployeeSelectedEvent">
      </employee-selector>
    </el-dialog>
    <el-dialog v-model="workExperienceAddVisible" v-if="workExperienceAddVisible" :title="workExperienceAddTitle" :top="dialogTop" :width="dialogWidth">
      <work-experience-add :id="selectedWorkExperienceId" @close-work-experience-add-event="handleCloseWorkExperienceAddEvent" @reset-work-experience-add-event="handleResetWorkExperienceAddEvent">
      </work-experience-add>
    </el-dialog>
    <el-dialog v-model="workExperienceViewVisible" v-if="workExperienceViewVisible" title="工作经历详情" :top="dialogTop" :width="dialogWidth">
      <work-experience-view :id="selectedWorkExperienceId" @close-work-experience-view-event="handleCloseWorkExperienceViewEvent">
      </work-experience-view>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, inject, toRefs} from 'vue';
import workExperienceApi from '@/api/workExperienceApi'
import type {WorkExperienceQueryForm} from "@/types/req/workExperienceQueryForm";
import type {WorkExperience} from "@/types/resp/workExperience";
import {ElMessage, ElMessageBox, type FormInstance} from "element-plus";
import type {Result} from "@/types/result";
import type {Page} from "@/types/page";
import { Search } from '@element-plus/icons-vue';
import EmployeeSelector from "@/views/employee/EmployeeSelector.vue";
import WorkExperienceAdd from "@/views/workExperience/WorkExperienceAdd.vue"
import WorkExperienceView from "@/views/workExperience/WorkExperienceView.vue"
import { exportToExcel } from '@/composables/exportUtil.ts'


const workExperienceQueryFormRef = ref<FormInstance | null>(null);
const workExperienceQueryForm = reactive<WorkExperienceQueryForm>({
  employeeId: 0,
  employeeName: '',
})

const state = reactive({
  loading: false,
  tableData: [] as WorkExperience[], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  pageSizes: [10, 20, 50]
})
const selectedWorkExperienceId = ref<number>(0)
const employeeSelectorVisible = ref<boolean>(false)
const workExperienceAddVisible = ref<boolean>(false)
const workExperienceViewVisible = ref<boolean>(false)
const workExperienceAddTitle = ref<string>('')
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')

const rules = reactive({
});

onMounted(() => {
  onSearch()
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
})

const getPageData = async () => {
  try {
    state.loading = true
    const resp: Result<Page<WorkExperience>> = await workExperienceApi.find(workExperienceQueryForm)
    if (resp && resp.code === 1) {
      if (resp.data) {
      const page: Page<WorkExperience> = resp.data
        if (page && page.list.length > 0) {
          state.tableData = page.list
          state.total = page.total
        }
      }
    }
  } catch (e) {
    console.log('获取数据异常', e)
  } finally {
    state.loading = false
  }
}
const onSearch = () => {
  getPageData()
}

const changePage = (val: number) => {
  state.currentPage = val
  getPageData()
}

const onReset = () => {
  if (workExperienceQueryFormRef.value) {
    workExperienceQueryFormRef.value.resetFields()
  }
  state.currentPage = 1
  getPageData()
}

const onAdd = () => {
  selectedWorkExperienceId.value = 0
  workExperienceAddVisible.value = true
  workExperienceAddTitle.value = '工作经历新增'
}
const editRow = (id: number) => {
  selectedWorkExperienceId.value = id
  workExperienceAddVisible.value = true
  workExperienceAddTitle.value = '工作经历编辑'
}
const delRow = (id: number) => {
  if (!id) {
    return
  }
  ElMessageBox.confirm(
    '确定要删除吗?',
    '删除提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    workExperienceApi.del(id)
      .then((resp) => {
        if (resp && resp.code === 1) {
          ElMessage.success('删除成功!')
          onSearch()
        } else {
          ElMessage.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
        }
      })
      .catch(error => {
        console.error('操作失败:', error)
      })
  }).catch(() => {})
}
const detailRow = (id:number) => {
  selectedWorkExperienceId.value = id
  workExperienceViewVisible.value = true
}

const findEmployee = () => {
  employeeSelectorVisible.value = true
}

const handleEmployeeSelectedEvent = (selectedEmployee: any) => {
  employeeSelectorVisible.value = false
  if (selectedEmployee && 'employeeId' in selectedEmployee && workExperienceQueryForm.employeeId !== selectedEmployee['employeeId']) {
    workExperienceQueryForm.employeeId = selectedEmployee['employeeId']
    workExperienceQueryForm.employeeName = selectedEmployee['employeeName']
  }
}

const handleCloseWorkExperienceViewEvent = () => {
  workExperienceViewVisible.value = false
}

const handleResetWorkExperienceAddEvent = () => {
  workExperienceAddTitle.value = '工作经历新增'
}

const handleCloseWorkExperienceAddEvent = (params: { search?: boolean } | undefined) => {
  if (params && params.search) {
    onSearch()
  }
  workExperienceAddVisible.value = false
}

const onExport = () => {
  const headers = ['员工姓名','公司名称','岗位','开始日期','结束日期','岗位职责']
  workExperienceApi.find(workExperienceQueryForm).then(data => {
    if (!data || !data.data || data.data.list.length < 1) {
      ElMessage.error('无数据导出')
      return
    }
    const exportData = []
    for (const d of data.data.list) {
      exportData.push([d.employeeName,d.company,d.position,d.startDate,d.endDate,d.responsibilities])
    }
    exportToExcel(headers, exportData)
  })
}
</script>

<style lang="scss">
</style>